<template>
    <Card class="no-border-card">
        <p slot="title">
            房源信息
        </p>

        <div class="c-extra-btn-group" slot="extra">
            <Button
                class="c-extra-btn"
                type="primary"
                v-if="homeInfo && disableFlag"
                @click="disableFlag=false">
                编辑
            </Button>
            <Button
                class="c-extra-btn"
                type="primary"
                v-if="(homeInfo && !disableFlag) || !homeInfo"
                @click="editInfo">
                保存
            </Button>
            <Button
                class="c-extra-btn"
                type="primary"
                v-if="homeInfo"
                @click="deleteHome(homeInfo.id)">
                删除
            </Button>
        </div>
        <Row :gutter="20" style="margin-bottom:20px;">
            <i-col span="6" v-if="homeType !== 'focus'">
                <Select
                    v-model="leaseType"
                    placeholder="租赁类型"
                    v-if="!homeInfo">
                    <Option :value="1">分租</Option>
                    <Option :value="2">整租</Option>
                </Select>
                <p v-else class="lease-type">租赁类型: {{this.homeInfo.lease_type === 1 ? '分租 (不支持公区预付费，公区不可入住租客)' : '整租 (不支持公摊，不支持租客入住房间)'}}</p>
            </i-col>
            <i-col span="6">
                <Select
                    v-model="parentHome"
                    @on-change="handleParentChange"
                    :disabled="branchIsRequired || isDisabled"
                    placeholder="房源归属">
                    <Option :value="1">总部</Option>
                    <Option :value="2">分店</Option>
                </Select>
            </i-col>
            <Col span="6" v-if="parentHome === 2">
                <!-- 编辑房间homeInfo状态!isDisabled下又是管家isKeeper则禁用 -->
                <Select
                    filterable
                    v-model="branch"
                    :placeholder="branchRequired"
                    :disabled="isDisabled || (homeInfo && !isDisabled === isKeeper) || parentHome !== 2">
                    <Option v-for="item in branches" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
            </Col>

            <Col span="6">
                <Input v-model.trim="homeName " placeholder="房源编号" :disabled="isDisabled"></Input>
            </Col>

        </Row>
        <Row v-if="!homeInfo && homeType !== 'focus'" style="margin-top: -10px;margin-bottom: 10px;color: #f00">
            {{leaseTypeTip}}
        </Row>

        <Row :gutter="16" style="margin-bottom:13px;" v-if="!isEdit">
            <Col span="4">
                <input
                    v-if="!isEdit"
                    class="ivu-input" ref="input"
                    v-model="block"
                    autocomplete="off"
                    :id="'input_id'+(homeInfo ? homeInfo.id : homeType)"
                    :name="'input_id'+(homeInfo ? homeInfo.id : homeType)"
                    placeholder="小区名称(可输入关键字搜索)" />
                <i-input
                    v-else
                    :disabled="isEdit"
                    v-model="block"></i-input>
            </Col>

            <Col span="4">
                <Select v-model="province" @on-change="selectProvince" :label-in-value="true" placeholder="省份/自治区" :disabled="isEdit">
                    <Option v-for="item in provinces" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
            </Col>

            <Col span="4">
                <Select v-model="city" @on-change="selectCity" :label-in-value="true" placeholder="城市/地区" :disabled="isEdit">
                    <Option v-for="item in cities" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
            </Col>

            <Col span="4">
                <Select v-model="area" :label-in-value="true" placeholder="区/县" :disabled="isEdit">
                    <Option v-for="item in areas" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
            </Col>
            <Col span="4">
                <Input v-model="street" placeholder="街道" :disabled="isEdit"></Input>
            </Col>

            <Col span="4">
                <Input v-model="doorNumber" placeholder="门牌号" :disabled="isEdit"></Input>
            </Col>
        </Row>

        <div class="whole-address" v-if="!isEdit">房源地址：<strong>{{ wholeAddress + this.street +  this.block + this.doorNumber }}</strong></div>
        <div class="whole-address" v-if="isEdit">房源地址：<strong>{{ wholeAddress + address }}</strong></div>

        <div class="address-tip" style="margin-bottom:0px" v-if="isEdit">为保障售后信息准确性，房源地址不支持修改, 如需修改请联系客服。</div>
    </Card>
</template>
<script>
/**
 * 店长、管理员、管家必须添加门店
 * 101 102 104
 */
import util from '@/libs/util'
import { http, api } from '@/libs/http'
import dataCenter from '@/libs/dataCenter'
export default {
  props: ['homeInfo', 'homeType', 'hasDevice'],
  data () {
    return {
      leaseType: 1, // 租赁类型
      branchIsRequired: false,
      provinces: [],
      province: '',

      cities: [],
      city: '',

      areas: [],
      area: '',

      street: '',
      block: '',

      branches: [],
      branch: null,
      homeName: '',
      doorNumber: '',
      address: '',

      disableFlag: true,
      emitData: '',
      parentHome: ''
    }
  },
  mounted () {
    this.getBranches()
    this.getProvice()
    this.initMap()
    if (this.homeInfo) {
      this.renderInfomation(this.homeInfo)
    }

    // console.log('this.homeInfo', this.homeInfo);
  },
  computed: {
    isKeeper () {
      const { roleId } = this.$store.state.user
      return roleId === 104 || roleId === 103 // 财务103也不行
    },
    leaseTypeTip () {
      return this.leaseType === 1
        ? '注：分租情况下，公区不可设置为预付费，且不可办理租客入住。新建成功后，不可修改。'
        : '注：整租情况下，公区可设置为预付费或后付费，可办理租客入住，公摊不可开启，房间不可办理租客入住。新建成功后，不可修改。'
    },
    wholeAddress () {
      let province = ''
      let city = ''
      let area = ''

      this.provinces.forEach(item => {
        if (item.id === this.province) {
          province = item.name
        }
      })

      this.cities.forEach(item => {
        if (item.id === this.city) {
          city = item.name
        }
      })

      this.areas.forEach(item => {
        if (item.id === this.area) {
          area = item.name
        }
      })

      this.emitData = {
        province,
        city,
        area,
        street: this.street || null,
        block: this.block || null,
        doorNumber: this.doorNumber || null,
        home_name: this.homeName,
        branch_id: this.branch
      }

      this.$emit('on-change', this.emitData)

      return '' + province + city + area
    },
    isEdit () {
      return !!this.homeInfo
    },
    isDisabled () {
      if (this.homeInfo && this.disableFlag) {
        return true
      } else {
        return false
      }
    },
    branchRequired () {
      const { roleId, branches } = this.$store.state.user
      if (roleId && [101, 102, 104].includes(roleId) && branches.length) {
        this.branchIsRequired = true
        this.parentHome = 2
        return '门店(必填)'
      }
      return '门店(必填)'
    }
  },
  methods: {
    handleParentChange (value) {
      if (value === 2) {
        this.branch = null
      } else {
        this.branch = 0
      }
    },
    initMap () {
      window.AMap.plugin(['AMap.Autocomplete'], () => {
        let autoOptions = {
          city: this.city,
          input: 'input_id' + (this.homeInfo ? this.homeInfo.id : this.homeType)
        }
        let autocomplete = new window.AMap.Autocomplete(autoOptions)

        window.AMap.event.addListener(autocomplete, 'select', async e => {
          const location = e.poi
          this.block = location.name
          this.province = ''
          this.city = ''
          this.area = ''
          this.street = typeof location.address === 'string' ? location.address : ''
          const province = this.provinces.find(p => location.district.includes(p.name))
          this.province = province.id
          await this.fetchCities(province.id)
          const city = this.cities.find(c => location.district.includes(c.name))
          if (!city) return
          this.city = city.id
          this.areas = []
          await this.fetchDistricts(city.id)
          const district = this.areas.find(d => location.district.includes(d.name))
          if (!district) return
          this.area = district.id
        })
      })
    },
    fetchCities (pid) {
      return new Promise(resolve => {
        dataCenter.getCities(this, pid, (res, err) => {
          if (res) {
            this.cities = res
          }
          resolve()
        })
      })
    },
    fetchDistricts (cid) {
      return new Promise(resolve => {
        dataCenter.getDistricts(this, cid, (res, err) => {
          if (res) {
            this.areas = res
          }
          resolve()
        })
      })
    },

    // 获取门店
    getBranches () {
      dataCenter.getStores(this, (res, err) => {
        if (err || !res) {
          return
        }
        this.branches.push(...res)
      })
    },

    // 获取省份
    getProvice () {
      dataCenter.getProvinces(this, (res, err) => {
        if (res) {
          this.provinces = res
        }
      })
    },

    selectProvince (province) {
      util.log(province)
      if (province && province.value) {
        this.cities = []
        this.city = ''
        this.areas = []
        this.area = ''
        dataCenter.getCities(this, province.value, (res, err) => {
          if (res) {
            this.cities = res
            if (!res.length) {
              this.$Message.info('暂不支持该地区')
            }
          }
        })
      } else {
        this.cities = []
      }
    },
    selectCity (city) {
      util.log('selectCity', city)
      this.areas = []
      this.area = ''
      if (city && city.value) {
        dataCenter.getDistricts(this, city.value, (res, err) => {
          if (res) {
            this.areas = res
            if (!res.length) {
              this.$Message.info('暂不支持该地区')
            }
          }
        })
      } else {
        this.areas = []
      }
    },

    renderInfomation (homeInfo) {
      // 显示下拉框地址
      let province
      let city
      let area
      if (homeInfo) {
        // 编辑的时候回显信息
        province = homeInfo.province
        city = homeInfo.city
        area = homeInfo.district
        this.street = homeInfo.street || ''
        this.block = homeInfo.block
        this.branch = homeInfo.branch_id
        this.homeName = homeInfo.home_name
        this.doorNumber = homeInfo.number || ''
        this.address = homeInfo.address || ''
        this.parentHome = homeInfo.branch_id ? 2 : 1
      }

      this.provinces.forEach(item => {
        if (item.name === province) {
          this.province = item.id
          this.renderCity(city, area)
        }
      })
    },
    renderCity (city, area) {
      dataCenter.getCities(this, this.province, (res, err) => {
        if (res) {
          this.cities = res
          this.cities.forEach(item => {
            if (item.name === city) {
              this.city = item.id
              this.renderArea(area)
            }
          })
        }
      })
    },
    renderArea (area) {
      dataCenter.getDistricts(this, this.city, (res, err) => {
        if (res) {
          this.areas = res
          this.areas.forEach(item => {
            if (item.name === area) {
              this.area = item.id
            }
          })
        }
      })
    },

    deleteHome (homeId) {
      this.$Modal.confirm({
        title: '删除房源',
        content: '确定要删除该房源吗?',
        okText: '删除',
        onOk: () => {
          this.delHomeConfirm(homeId)
        }
      })
    },
    delHomeConfirm (homeId) {
      http.request(this, api.home_del, [homeId], null, (res, err) => {
        if (err || !res) {
          return
        }
        this.$Message.success('删除房源成功!')
        this.$emit('on-delete-home', homeId)
      })
    },

    editInfo () {
      let areaInfo = this.emitData
      // console.log(this.branch);
      const checkForm = [
        {
          valid: !(this.branch === 0 || this.branch),
          msg: '请选择门店'
        },
        {
          valid: !areaInfo.home_name,
          msg: '请填写房源编号'
        },
        {
          valid: !areaInfo.province,
          msg: '请选择省份'
        },
        {
          valid: !areaInfo.city,
          msg: '请选择城市'
        },
        {
          valid: !areaInfo.area,
          msg: '请选择地区'
        },
        {
          valid: !areaInfo.block && !this.isEdit,
          msg: '请填写小区'
        },
        {
          valid: !areaInfo.street && !this.isEdit,
          msg: '请填写街道'
        },
        {
          valid: !areaInfo.doorNumber && !this.isEdit,
          msg: '请填写门牌号'
        }
      ]

      if (!this.homeInfo) {
        checkForm.push({
          valid: !this.leaseType,
          msg: '请选择租赁类型'
        })
      }
      if (
        util.formErrorHandler(checkForm)
      ) {
        return
      }
      this.$emit('on-edit-info', this.leaseType)
      this.disableFlag = true
    }
  }
}
</script>

<style lang="less">
.select-top-btn {
    position: absolute;
    right: 0px;
    top: 0px;
    &.add-floor {
        right: 110px;
    }
}
.range {
    margin-bottom: 20px;
}
.bg {
    background: #efeff1;
    margin-bottom: 20px;
    padding-top: 20px;
    padding-bottom: 20px;
}
.margin-left-10 {
    margin-left: 10px;
}
.btn-in-top-del {
    border-radius: 0;
}
.ivu-card-head {
    overflow: hidden;
}
.c-extra-btn-group {
    overflow: hidden;
    margin-right: -20px;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
}

.c-extra-btn {
    vertical-align: top;
    height: 50px;
    margin-left: 5px;
    border: 0;
    border-radius: 0;
}
.whole-address{
    margin-bottom: 0;
    strong{
        font-size: 14px;
    }
}
.address-tip{
    margin-top: 6px;
    color: #df4242;
}

.lease-type {
    font-weight: 800;
    line-height: 40px;
    font-size: 14px;
}
</style>
